package ebcs.scan.controller.sys;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import ebcs.app.auto.transmodel.sys.UserInforReqModel;
import ebcs.app.auto.transmodel.sys.UserPasswordReqModel;
import ebcs.database.bean.sys.PaUser;
import ebcs.database.bean.sys.PaUserRole;
import ebcs.database.service.sys.IUserManagerService;
import ebcs.database.service.sys.IUserRoleManagerService;
import ebcs.scan.bean.sys.SysUserInfor;
import ebcs.scan.common.consts.KPlatSysConsts;
import ebcs.scan.common.consts.UserStatus;
import jplat.core.trans.JAppBaseService;
import jplat.core.trans.JAppContext;
import jplat.core.trans.JAppContextFactory;
import jplat.error.exception.JSystemException;
import jplat.error.exception.JTransException;
import jplat.tools.coder.MD5Utils;
import jplat.tools.string.DateUtil;

/***
 * 用户管理
 * 
 * @author chenzhuo
 * @comment
 */
@Controller
public class UserManagerCtrl extends JAppBaseService {
	private Logger logger = Logger.getLogger(UserManagerCtrl.class);
	protected JAppContextFactory serviceFactory = new JAppContextFactory();
	// 数据库库服务.
	@Autowired
	public IUserManagerService userService;
	
	@Autowired
	public IUserRoleManagerService userRoleService;

	/**
	 * 添加用户
	 */
	@RequestMapping("/sys/user/addUser.do")
	public void addUser(HttpServletRequest request, HttpServletResponse response)
			throws JTransException, JSystemException {
		JAppContext context = serviceFactory.buildAppContextWithUser(request, response); // buildAppContextWithUser
																							// 自带客户信息.
		UserInforReqModel userReq = context.obtainReqModel(UserInforReqModel.class);
		
		//userNo 不用重复注册
		List userList = this.userService.seachUserInforByUserNo(userReq.getUserNo());
		if(userList.size()>0){
			throw new JTransException(KPlatSysConsts.SYS_ERROR_USER, "该用户信息已经重复注册，请重新填写用户号！");
		}
		
		SysUserInfor userInfor = context.getUserInfo();
		PaUser paUser = new PaUser();
		paUser.setUserNo(userReq.getUserNo());
		paUser.setUserName(userReq.getUserName());
		paUser.setCreateDate(DateUtil.todayStr());
		paUser.setCreateUser(userReq.getUserNo());
		paUser.setEmail(userReq.getEmail());
		paUser.setPhone(userReq.getPhone());
		paUser.setPassword(userReq.getPassword());
		paUser.setEnabled(userReq.getEnabled());
		paUser.setAgenId(userReq.getAgenId());
		paUser.setUserstatus(UserStatus.USER_STATE_LIVE.getValue());//用户注销状态为有效
		String parseMD5Passwd = "";
		try {
			parseMD5Passwd = MD5Utils.md5(userReq.getPassword());
		} catch (Exception e) {
			logger.error("用户密码转换错误:" + e.getMessage());
			throw new JSystemException(KPlatSysConsts.SYS_ERROR_USER, "用户密码转换错误");
		}
		paUser.setPassword(parseMD5Passwd);
		int i = this.userService.insert(paUser);
		if(i==0){
			throw new JTransException(KPlatSysConsts.SYS_ERROR_USER, "用户信息新增失败！请联系管理员！");
		}
		//添加角色信息
		List<String> roleList = userReq.getRoleIdList();
		//新增到用户角色表中
		for(String roleId : roleList) {
			PaUserRole userRole = new PaUserRole();
			userRole.setRoleId(roleId);
			userRole.setUserId(paUser.getUserId()+"");
			userRoleService.insertUserRole(userRole);
		}
		
		Map rsModel = new HashMap();
		context.buildAppResponse(null);
	}

	/**
	 * 用户注销
	 */
	@RequestMapping("/sys/user/logOffUser.do")
	public void logOffUser(HttpServletRequest request, HttpServletResponse response)
			throws JTransException, JSystemException {
		JAppContext context = serviceFactory.buildAppContextWithUser(request, response); // buildAppContextWithUser
																						// 自带客户信息.
		UserInforReqModel userReq = context.obtainReqModel(UserInforReqModel.class);

		PaUser user = new PaUser();
		user.setUserId(userReq.getUserId());
		user.setUserstatus(UserStatus.USER_STATE_OVER.getValue());// 注销状态
		int i = this.userService.updateUserInfor(user);
		if (i != 1) {
			logger.error("用户注销失败,不是更新单条记录");
			throw new JSystemException(KPlatSysConsts.SYS_ERROR_USER, "用户注销失败,请联系管理员");
		}
		Map rsModel = new HashMap();
		context.buildAppResponse(null);
	}

	/**
	 * 用户更新
	 */
	@RequestMapping("/sys/user/updateUser.do")
	public void updateUser(HttpServletRequest request, HttpServletResponse response)
			throws JTransException, JSystemException {
		JAppContext context = serviceFactory.buildAppContextWithUser(request, response); // buildAppContextWithUser
		UserInforReqModel userReq = context.obtainReqModel(UserInforReqModel.class);
		SysUserInfor userInfor = context.getUserInfo();
		
		//查询userNo 的用户
		List<PaUser> userList = this.userService.seachUserInforByUserNo(userReq.getUserNo());
		if(userList.size()>0){
			PaUser userDb  = userList.get(0);
			if(userDb.getUserId()!=userReq.getUserId()){
				throw new JSystemException(KPlatSysConsts.SYS_ERROR_USER, "用户编号为["+userDb.getUserNo()+"]更新信息重复，请确认！");
			}
		}
		PaUser paUser = new PaUser();
		paUser.setUserId(userReq.getUserId());
		paUser.setUserNo(userReq.getUserNo());
		paUser.setUserName(userReq.getUserName());
		paUser.setModifyDate(DateUtil.todayStr());
		paUser.setModifyUser(userInfor.getUserNo());
		paUser.setEmail(userReq.getEmail());
		paUser.setPhone(userReq.getPhone());
		paUser.setAgenId(userReq.getAgenId());
		paUser.setEnabled(userReq.getEnabled());
		if(StringUtils.isNotEmpty(userReq.getPassword())){
			String parseMD5Passwd = "";
			try {
				parseMD5Passwd = MD5Utils.md5(userReq.getPassword());
			} catch (Exception e) {
				logger.error("用户密码转换错误:" + e.getMessage());
				throw new JSystemException(KPlatSysConsts.SYS_ERROR_USER, "用户密码转换错误");
			}
			paUser.setPassword(parseMD5Passwd);
			paUser.setPasswordModifyDate(DateUtil.todayStr());
		}
		int i = this.userService.updateUserInfor(paUser);
		if(i==0) {
			throw new JTransException(KPlatSysConsts.SYS_ERROR_USER, "用户信息修改失败！请联系管理员！");
		}
		
		//添加角色信息
		List<String> roleList = userReq.getRoleIdList();
		
		//清除掉当前用户的角色信息
		this.userRoleService.deleteUserRole(paUser.getUserId()+"");
		//更新到用户角色表中
		for(String roleId : roleList) {
			PaUserRole userRole = new PaUserRole();
			userRole.setRoleId(roleId);
			userRole.setUserId(paUser.getUserId()+"");
			userRoleService.insertUserRole(userRole);
		}
 		Map rsModel = new HashMap();
		context.buildAppResponse(null);
	}
	
	/**
	 * 用户密码更新
	 */
	@RequestMapping("/sys/user/updateUserPassword.do")
	public void updateUserPassword(HttpServletRequest request, HttpServletResponse response)
			throws JTransException, JSystemException {
		JAppContext context = serviceFactory.buildAppContextWithUser(request, response);
		UserPasswordReqModel userReq = context.obtainReqModel(UserPasswordReqModel.class);
		SysUserInfor userInfor = context.getUserInfo();
		PaUser userSearchInfor = this.userService.seachUserInforByUseId(userInfor.getUserId());
		
		if(!userReq.getOldPassword().equals(userSearchInfor.getPassword())){
			throw new JTransException(KPlatSysConsts.SYS_ERROR_USER,"原始密码错误,请重新输入！");
		}
		PaUser paUser = new PaUser();
		paUser.setUserId(userReq.getUserId());
		String parseMD5Passwd = "";
		try {
			parseMD5Passwd = MD5Utils.md5(userReq.getNewPassword());
		} catch (Exception e) {
			logger.error("用户密码转换错误:" + e.getMessage());
			throw new JSystemException(KPlatSysConsts.SYS_ERROR_USER, "用户密码转换错误");
		}
		paUser.setPassword(parseMD5Passwd);
		paUser.setPasswordModifyDate(DateUtil.todayStr());
		this.userService.updateUserInfor(paUser);
	}
	
	/**
	 * 查看用户列表
	 */
	@RequestMapping("/sys/user/searchUserList.do")
	public void searchUserList(HttpServletRequest request, HttpServletResponse response)
			throws JTransException, JSystemException {
		JAppContext context = serviceFactory.buildAppContextWithUser(request, response);
 		
	}
	
	
	/**
	 * 查看用户明细
	 */
	@RequestMapping("/sys/user/searchUserDetail.do")
	public void searchUserDetail(HttpServletRequest request, HttpServletResponse response)
			throws JTransException, JSystemException {
		JAppContext context = serviceFactory.buildAppContextWithUser(request, response);
 		 
	}

}
